package com.cn.parks.servlet;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.cn.parks.dao.*;
import com.cn.parks.dao.impl.*;
import com.cn.parks.entity.TempParking;
import com.cn.parks.entity.UserCar;
import com.cn.parks.util.Result;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Date;
import java.util.UUID;

/**
 * 用户车辆管理Servlet
 */
@WebServlet("/userCar/*")
public class UserCarServlet extends HttpServlet {
    private UserCarDao userCarDao = new UserCarDaoImpl();
    private UserDao userDao = new UserDaoImpl();
    private ParkingSeatDao parkingSeatDao = new ParkingSeatDaoImpl();
    private TempParkingDao tempParkingDao = new TempParkingDaoImpl();
    private FixedParkingDao fixedParkingDao = new FixedParkingDaoImpl();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=utf-8");
        
        String pathInfo = request.getPathInfo();
        try {
            if ("/getAll".equals(pathInfo)) {
                // 获取所有车辆
                response.getWriter().write(JSON.toJSONString(Result.success(userCarDao.getAll())));
            } else if ("/getById".equals(pathInfo)) {
                // 根据ID获取车辆
                Integer carId = Integer.parseInt(request.getParameter("carId"));
                response.getWriter().write(JSON.toJSONString(Result.success(userCarDao.getById(carId))));
            } else if ("/getByCarNumber".equals(pathInfo)) {
                // 根据车牌号搜索
                String carNumber = request.getParameter("carNumber");
                response.getWriter().write(JSON.toJSONString(Result.success(userCarDao.getByCarNumber(carNumber))));
            } else if ("/getByUserId".equals(pathInfo)) {
                // 获取用户的车辆
                Integer userId = Integer.parseInt(request.getParameter("userId"));
                response.getWriter().write(JSON.toJSONString(Result.success(userCarDao.getByUserId(userId))));
            }
        } catch (Exception e) {
            response.getWriter().write(JSON.toJSONString(Result.error(e.getMessage())));
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=utf-8");
        
        String pathInfo = request.getPathInfo();
        try {
            if ("/insert".equals(pathInfo)) {
                // 添加车辆
                String requestBody = request.getReader().readLine();
                UserCar car = JSON.parseObject(requestBody, UserCar.class);
                
                // 检查用户是否存在
                if (userDao.getById(car.getUserId()) == null) {
                    response.getWriter().write(JSON.toJSONString(Result.error("用户不存在")));
                    return;
                }
                
                // 检查车牌号是否已存在
                if (userCarDao.getByCarNum(car.getCarNumber()) != null) {
                    response.getWriter().write(JSON.toJSONString(Result.error("车牌号已存在")));
                    return;
                }

                // 检查车位是否存在
                if (parkingSeatDao.getBySeatNum(car.getSeatNum()) == null) {
                    response.getWriter().write(JSON.toJSONString(Result.error("车位不存在")));
                    return;
                }

                if (parkingSeatDao.getBySeatNum(car.getSeatNum())== 1){
                    response.getWriter().write(JSON.toJSONString(Result.error("车位已被使用")));
                    return;
                }
                if (parkingSeatDao.getBySeatNum(car.getSeatNum())==2){
                    response.getWriter().write(JSON.toJSONString(Result.error("车位维护中")));
                    return;
                }
                if ( parkingSeatDao.getSeatTag(car.getSeatNum()).equals("")){
                    response.getWriter().write(JSON.toJSONString(Result.error("车位状态异常")));
                    return;
                }else if (parkingSeatDao.getSeatTag(car.getSeatNum()).equals("固定车位")){
                    car.setCarType(1);
                }else if (parkingSeatDao.getSeatTag(car.getSeatNum()).equals("VIP车位")){
                    car.setCarType(2);
                }else {
                    car.setCarType(3);
                    TempParking tempParking = new TempParking();
                    tempParking.setUserId(car.getUserId());
                    tempParking.setCarNum(car.getCarNumber());
                    tempParkingDao.insert(tempParking);
                }
                //添加车辆
                userCarDao.insert(car);
                //获取刚添加的车辆ID
                car.setCarId(userCarDao.getByCarId(car.getCarNumber()));
                //更新车位状态：占用，车辆ID 车牌号，用户ID
                parkingSeatDao.updateSeatState(car.getSeatNum(), car.getCarId(), car.getCarNumber(), car.getUserId());
                response.getWriter().write(JSON.toJSONString(Result.success()));
            } else if ("/update".equals(pathInfo)) {
                // 更新车辆
                UserCar car = JSON.parseObject(request.getReader().readLine(), UserCar.class);
                if (userDao.getById(car.getUserId()) == null){
                    response.getWriter().write(JSON.toJSONString(Result.error("用户不存在")));
                    return;
                }
                if (parkingSeatDao.getBySeatNum(car.getSeatNum()) == null){
                    response.getWriter().write(JSON.toJSONString(Result.error("车位不存在")));
                    return;
                }
                if (parkingSeatDao.getBySeatNum(car.getSeatNum())== 1){
                    response.getWriter().write(JSON.toJSONString(Result.error("车位已被使用")));
                    return;
                }
                if (parkingSeatDao.getBySeatNum(car.getSeatNum())==2){
                    response.getWriter().write(JSON.toJSONString(Result.error("车位维护中")));
                    return;
                }
                if ( parkingSeatDao.getSeatTag(car.getSeatNum()).equals("")){
                    response.getWriter().write(JSON.toJSONString(Result.error("车位状态异常")));
                    return;
                }else if (parkingSeatDao.getSeatTag(car.getSeatNum()).equals("固定车位")){
                    car.setCarType(1);
                }else if (parkingSeatDao.getSeatTag(car.getSeatNum()).equals("VIP车位")){
                    car.setCarType(2);
                }else {
                    car.setCarType(3);
                }

                //更新车辆
                userCarDao.update(car);
                //获取车辆ID
                car.setCarId(userCarDao.getByCarId(car.getCarNumber()));
                //更新车位状态：占用，车辆ID 车牌号，用户ID
                parkingSeatDao.updateSeatStateByCarId(car.getCarId());
                parkingSeatDao.updateSeatState(car.getSeatNum(), car.getCarId(), car.getCarNumber(), car.getUserId());
                response.getWriter().write(JSON.toJSONString(Result.success()));
            } else if ("/deleteById".equals(pathInfo)) {
                // 删除车辆
                Integer carId = JSON.parseObject(request.getReader().readLine()).getInteger("carId");
                //更新车位状态：空闲
                parkingSeatDao.updateSeatStateByCarId(carId);
                userCarDao.deleteById(carId);
                response.getWriter().write(JSON.toJSONString(Result.success()));
            } else if ("/updateStatus".equals(pathInfo)) {
                // 更新车辆状态
                Integer carId = Integer.parseInt(request.getParameter("carId"));
                Integer status = Integer.parseInt(request.getParameter("status"));
                userCarDao.updateStatus(carId, status);
                response.getWriter().write(JSON.toJSONString(Result.success()));
            }
        } catch (Exception e) {
            response.getWriter().write(JSON.toJSONString(Result.error(e.getMessage())));
        }
    }
} 